package com.theme.common.third.weather;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.theme.common.base.DateHandler;
import com.theme.common.base.DateUtil;
import com.theme.common.base.http.HttpHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @区号地址：https://lbs.amap.com/api/webservice/download
 * @文档地址：https://blog.csdn.net/weixin_45707639/article/details/125469783
 * @author: 可乐加糖
 * @create: 2022-07-19 09:07
 * @Description: 高德天气组件
 */
@Slf4j
public class WeatherHandler {

    private static final String AMAP_KEY = "7934150776134fdda29cd1bcbc73ee7e";

    /**
     * 返回预报天气
     * @param adCode
     * @param amapKey
     * @return
     */
    public static List<Weather>  getWeather(String adCode,String amapKey) {
        try {
            WeatherDTO weatherDTO = getWeatherAll(adCode,amapKey);
            ArrayList<Forecast> forecasts = weatherDTO.getForecasts();
            if (forecasts == null || forecasts.size() <= 0){
                return null;
            }
            Forecast one = forecasts.get(0);
            ArrayList<Cast> casts = one.getCasts();
            if (casts == null && casts.size() > 0) {
                return null;
            }
            List<Weather> weatherList = new ArrayList<>();
            casts.forEach(cast -> {
                Weather weather = new Weather();
                BeanUtils.copyProperties(cast,weather);
                weather.setAdcode(adCode);
                weather.setCity(one.getCity());
                weather.setReporttime(one.getReporttime());
                weather.setProvince(one.getProvince());
                weatherList.add(weather);
            });
            return weatherList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null ;
    }

    /**
     * 返回实时天气
     * @param adCode
     * @param amapKey
     * @return
     */
    public static Live getLive(String adCode, String amapKey) {
        try {
            WeatherDTO weatherDTO = getWeatherBase(adCode,amapKey);
            ArrayList<Live> lives = weatherDTO.getLives();
            if (lives == null || lives.size() <= 0){
                return null;
            }
            Live live = lives.get(0);
            return live;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null ;
    }

    /**
     *  //#返回预报天气
     *  //https://restapi.amap.com/v3/weather/weatherInfo?city=<adcode>&key=<用户key>&extensions=all
     * @param adCode 区号
     * @return
     * @throws IOException
     */
    public static WeatherDTO getWeatherAll(String adCode,String amapKey) throws IOException {



        String url = "https://restapi.amap.com/v3/weather/weatherInfo?city=" + adCode + "&key=" + amapKey + "&extensions=all";

        String response = HttpHandler.doGetStr2(url);

        WeatherDTO weather = JSON.parseObject(response, WeatherDTO.class);;

        return weather;
    }

    /**
     * //返回实况天气
     * //https://restapi.amap.com/v3/weather/weatherInfo?city=<adcode>&key=<用户key>&extensions=base
     * @param adCode 区号
     * @return
     * @throws IOException
     */
    public static WeatherDTO getWeatherBase(String adCode,String amapKey) throws IOException {

        String url = "https://restapi.amap.com/v3/weather/weatherInfo?city=" + adCode + "&key=" + amapKey + "&extensions=base";

        String response = HttpHandler.doGetStr2(url);

        WeatherDTO weather = JSON.parseObject(response, WeatherDTO.class);;

        return weather;
    }

    /**
     * 将json对象转为可读的html文本，+br处理
     *
     * @param adCode
     * @return
     * @throws IOException
     */
    public static String getWeatherStr(String adCode,String amapKey) {
        try {
            WeatherDTO weatherDTO = getWeatherAll(adCode,amapKey);
            ArrayList<Forecast> forecasts = weatherDTO.getForecasts();
            Forecast one = forecasts.get(0);
            ArrayList<Cast> casts = one.getCasts();
            String content = "";
            if (casts == null) {
                content = "上方云层异常，疯狂布朗运动ing，暂无天气预报更新！————404";
                return content;
            }
            content = "地区：<b>" + one.getCity() + "</b>，更新时间：" + one.getReporttime() + "<br>";
            for (Cast cast : casts) {
                content += cast.getDate() + "————天气：" + cast.getDayweather() + "；气温：" + cast.getNighttemp() + "~" + cast.getDaytemp() + "℃；风力：" + cast.getDaypower() + "级" + cast.getDaywind() + "风<br>";
            }
            return content;
        } catch (IOException e) {
            return "上方云层异常，疯狂布朗运动ing，暂无天气预报更新！————403";
        }
    }

    public static void main(String[] args) throws IOException {
        //目前的日期
        //湖里区	350206	0592
        //集美区	350211	0592
        //同安区	350212	0592

//        Live live = getLive("330100",AMAP_KEY);
//        System.out.println("实时天气：");
//        String liveContent = "地区：<b>" + live.getCity() + "</b>，更新时间：" + live.getReporttime() + "<br>";
//        liveContent += "————天气：" + live.getWeather() + "；气温：" + live.getTemperature() + "~" + live.getHumidity() + "℃；风力：" + live.getWindpower() + "级" + live.getWinddirection() + "风<br>";
//        System.out.println(liveContent);

        List<Weather> weathers = getWeather("330100", AMAP_KEY);
        System.out.println("预告天气：");
        for (Weather weather : weathers) {
            String futureContent = "地区：<b>" + weather.getCity() + "</b>，更新时间：" + weather.getReporttime() + "<br>";
            futureContent += weather.getDate() + "————天气：" + weather.getDayweather() + "；气温：" + weather.getNighttemp() + "~" + weather.getDaytemp() + "℃；风力：" + weather.getDaypower() + "级" + weather.getDaywind() + "风<br>";
            System.out.println(futureContent);
        }
    }

    public static WeatherResult WeatherForApple(String latitude, String longitude, String token) {
//        String response = HttpHandler.doGetStr3("https://weatherkit.apple.com/api/v1/availability/"+latitude+"/"+longitude+"?country=CN",token);
        //获取明天日期的date

//        Date tomorrow = DateHandler.addNDayFromToDate(1);
        String tomerrowStr = DateHandler.DateToFormatStr(new Date(), DateHandler.DATE_PATTERN);
        String response = HttpHandler.doGetStr3("https://weatherkit.apple.com/api/v1/weather/zh-CN/" + latitude + "/" + longitude + "?timezone=Asia/Shanghai&dataSets=forecastDaily,currentWeather&dailyStart="+tomerrowStr, token);
        log.info("weather:{}",response);
        WeatherResult result = new WeatherResult();
        try {
            AppleWeatherHeadResult appleWeatherHeadResult = JSONObject.parseObject(response, AppleWeatherHeadResult.class);

            WeatherCityForJson toDayInfo = new WeatherCityForJson();

            toDayInfo.setWendu(Math.round(Double.parseDouble(appleWeatherHeadResult.getCurrentWeather().getTemperature()))+"℃");
            toDayInfo.setFl(WeatherUtils.windSpeedToScale(appleWeatherHeadResult.getCurrentWeather().getWindSpeed()));
            toDayInfo.setType(WeatherUtils.weatherTypeToString(appleWeatherHeadResult.getCurrentWeather().getConditionCode()));
            String ymd = DateHandler.DateToFormatStr(appleWeatherHeadResult.getCurrentWeather().getAsOf(), DateHandler.FORMAT_GENERAL1);
            toDayInfo.setYmd(ymd);
            toDayInfo.setDate(ymd.split("-")[2]);
            //获取当前date是星期几
            toDayInfo.setWeek(DateHandler.getWeekOfDate(appleWeatherHeadResult.getCurrentWeather().getAsOf()));

            ArrayList<WeatherResult.InfoDay> forecast = new ArrayList<>();

            int length =  appleWeatherHeadResult.getForecastDaily().getDays().size()>8?8:appleWeatherHeadResult.getForecastDaily().getDays().size();

            for (int i=0;i<appleWeatherHeadResult.getForecastDaily().getDays().size();i++){
                //date时间大于今天
                if (DateHandler.isDayuToday(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getForecastStart())){
                    WeatherResult.InfoDay info = new WeatherResult.InfoDay();
                    info.setWendu("");
                    info.setHigh(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getTemperatureMax()+"℃");
                    info.setLow(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getTemperatureMin()+"℃");
                    info.setType(WeatherUtils.weatherTypeToString(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getConditionCode()));
                    info.setFl(WeatherUtils.windSpeedToScale(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getWindSpeedAvg()));
                    String ymd2 = DateHandler.DateToFormatStr(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getForecastStart(), DateHandler.FORMAT_GENERAL1);
                    info.setYmd(ymd2);
                    info.setDate(ymd2.split("-")[2]);
                    info.setWeek(DateHandler.getWeekOfDate(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getForecastStart()));
                    forecast.add(info);
                }else{
                    //判断是否是今天
                    if (DateHandler.DateToFormatStr(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getForecastStart(),DateHandler.FORMAT_GENERAL1)
                            .equals(DateHandler.DateToFormatStr(new Date(),DateHandler.FORMAT_GENERAL1))){

                        toDayInfo.setLow(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getTemperatureMin()+"℃");
                        toDayInfo.setHigh(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getTemperatureMax()+"℃");

                        WeatherResult.InfoDay info = new WeatherResult.InfoDay();
                        info.setWendu(Math.round(Double.parseDouble(appleWeatherHeadResult.getCurrentWeather().getTemperature()))+"℃");
                        info.setHigh(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getTemperatureMax()+"℃");
                        info.setLow(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getTemperatureMin()+"℃");
                        info.setType(WeatherUtils.weatherTypeToString(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getConditionCode()));
                        info.setFl(WeatherUtils.windSpeedToScale(appleWeatherHeadResult.getCurrentWeather().getWindSpeed()));
                        String ymd2 = DateHandler.DateToFormatStr(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getForecastStart(), DateHandler.FORMAT_GENERAL1);
                        info.setYmd(ymd2);
                        info.setDate(ymd2.split("-")[2]);
                        info.setWeek(DateHandler.getWeekOfDate(appleWeatherHeadResult.getForecastDaily().getDays().get(i).getForecastStart()));
                        forecast.add(info);
                    }



                }

            }

            result.setForecast(forecast);
            result.setToDayInfo(toDayInfo);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }




        return result;
    }

        //https://www.sojson.com/api/weather.html
    public static WeatherResult WeatherForThird(String cityCode){
        String response = HttpHandler.doGetStr2("http://t.weather.sojson.com/api/weather/city/"+cityCode);
        WeatherForJsonRDTO weather = JSON.parseObject(response, WeatherForJsonRDTO.class);;

        if (!weather.getStatus().equals("200")){
            return null;
        }
        //获取当前的日期
        Calendar cal1 = Calendar.getInstance();
//        int day = cal1.get(Calendar.DAY_OF_MONTH);

        Date currentTime = new Date();
        String day =   DateHandler.DateToFormatStr(currentTime,"dd");

        log.info("day : "+day);


        WeatherResult result = new WeatherResult();
        ArrayList<WeatherResult.InfoDay> resultInfoList = new ArrayList<>();
        for (int i=0;i<weather.getData().getForecast().size();i++){
            if (i == 7){
                break;
            }
            WeatherResult.InfoDay resultInfo = new WeatherResult.InfoDay();
            //判断在当天的日期里把当前温度填充进去
            if (weather.getData().getForecast().get(i).getDate().equals(day)){
                resultInfo.setWendu(weather.getData().getWendu());

                WeatherCityForJson todayinfo = new WeatherCityForJson();
                todayinfo.setWendu(weather.getData().getWendu());
                todayinfo.setFl(weather.getData().getForecast().get(i).getFl());
                todayinfo.setHigh(weather.getData().getForecast().get(i).getHigh().replace("高温","").trim());
                todayinfo.setLow(weather.getData().getForecast().get(i).getLow().replace("低温","").trim());
                todayinfo.setDate(weather.getData().getForecast().get(i).getDate());
                todayinfo.setType(weather.getData().getForecast().get(i).getType());
                todayinfo.setYmd(weather.getData().getForecast().get(i).getYmd());
                todayinfo.setWeek(weather.getData().getForecast().get(i).getWeek());
                todayinfo.setCity(weather.getCityInfo().getCity());
                todayinfo.setParent(weather.getCityInfo().getParent());
                result.setToDayInfo(todayinfo);
            }else{
                resultInfo.setWendu("0");
            }
            resultInfo.setFl(weather.getData().getForecast().get(i).getFl());
            resultInfo.setHigh(weather.getData().getForecast().get(i).getHigh().replace("高温","").trim());
            resultInfo.setLow(weather.getData().getForecast().get(i).getLow().replace("低温","").trim());
            resultInfo.setDate(weather.getData().getForecast().get(i).getDate());
            resultInfo.setType(weather.getData().getForecast().get(i).getType());
            resultInfo.setYmd(weather.getData().getForecast().get(i).getYmd());
            resultInfo.setWeek(weather.getData().getForecast().get(i).getWeek());
            resultInfoList.add(resultInfo);
        }
         result.setForecast(resultInfoList);
        return result;
    }


}
